import pickle
import time

import pymysql
import redis


def load_depts_from_db():
    conn = pymysql.connect(host='120.77.222.217', port=3306,
                           user='root', password='123456',
                           database='hrs', charset='utf8')
    depts = ()
    try:
        with conn.cursor() as cursor:
            cursor.execute('select dno, dname, dloc from tb_dept')
            depts = cursor.fetchall()
    except pymysql.MySQLError as err:
        print(err)
    finally:
        conn.close()
    return depts


def main():
    client = redis.Redis(host='120.77.222.217', port=6379, password='1qaz2wsx')
    start = time.time()
    data = client.get('depts')
    if data:
        depts = pickle.loads(data)
    else:
        depts = load_depts_from_db()
        client.set('depts', pickle.dumps(depts))
    end = time.time()
    print(depts)
    print(f'执行时间: {end - start}秒')


if __name__ == '__main__':
    main()
